/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.dataset.netflow;
import java.util.*;
import java.io.*;

public class NetflowBuilder {

    public static void main(String[] args) {
        try {
            String lfapDirPath = "/n/lfap/flows/";
            String startDate = "20050101";
            String endDate = "";
            if (args.length > 2)
                startDate = args[2];
            if (args.length > 3)
                endDate = args[3];
            if (args.length < 2) {
                System.out
                        .println("Usage: java LFAPBuilder built_list server [startdate=YYYYMMDD [enddate=YYYYMMDD]]");
                return;
            }
            String host = args[1];
            //String tempFilePath = args[2];
            while (true) {
                Vector<NetflowLog> temp = new Vector<NetflowLog>();
                LineNumberReader in = new LineNumberReader(new FileReader(args[0]));
                String line = in.readLine();
                while (line != null) {

                    NetflowLog log = NetflowLog.generate(line);
                    if (log != null) {
                        temp.addElement(log);
                    }
                    line = in.readLine();
                }
                in.close();

                NetflowLog[] entries = new NetflowLog[temp.size()];
                for (int i = 0; i < entries.length; i++) {
                    entries[i] = (NetflowLog) temp.elementAt(i);
                }
                // Arrays.sort(entries, new LFAPLogComparator());
                Arrays.sort(entries);

                // LFAPFileFilter filter = new LFAPFileFilter();
                File lfapDir = new File(lfapDirPath);
                File[] files = lfapDir.listFiles(new NetflowFileFilter(startDate, endDate));
                if (files == null) {
                    System.err.println("No files! This is rather bad");
                    System.exit(0);
                }
 
                Arrays.sort(files);
                boolean didSomething = false;
                for (int i = files.length - 1; i > 0; i--) {
                    if (didSomething) {
                        break;
                    }
                    String filePath = files[i].getAbsolutePath();
                    System.out.println(filePath);
                    boolean found = false;
                    for (int j = 0; j < entries.length; j++) {
                        if (filePath.startsWith(entries[j].filePath)) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) { // Need to process
                        String exec = "";
                        int val = 0;
                        didSomething = true;
                        NetflowLog log = NetflowLog.generate(files[i], files);
                        String logDateStr = log.getDateStr();
                        boolean withinDateRange = true;


                        if (withinDateRange) {

                            File f = new File(log.filePath);
                            System.out.println(f.getAbsolutePath());
                            String fileName = f.getName();
                            System.out.println(fileName);
                            String[] time = fileName.substring(fileName.indexOf("_") + 1, fileName.indexOf("-")).split(
                                    ":");
                            int hour = Integer.parseInt(time[0]);
                            int min = Integer.parseInt(time[1]);
                            int sec = Integer.parseInt(time[2]);
                            long size = 0;
                            do {
                                if (size != 0)
                                    System.out.println("Waiting while being zipped.");
                                size = f.length();
                                Process p = Runtime.getRuntime().exec("perl sleep.pl");
                                p.waitFor();
                            } while (f.length() != size); // Checks that the
                                                            // file is not being
                                                            // zipped.

                            long ts1 = System.currentTimeMillis();
                            long ts2 = System.currentTimeMillis();
                            Process p = null;
                            ts1 = ts2;
                            String catExec = "zcat";
                            if (!log.filePath.endsWith(".gz"))
                                catExec = "cat";
                            exec = catExec
                                    + " "
                                    + log.filePath
                                    + " | flow-print   | perl dataclient_netflow.pl "
                                    + host + ":9097 " + log.month + "/" + log.day + "/" + log.year + " " + hour + ":"
                                    + min + ":" + sec + " " + log.run + " ds";
                            System.out.println(exec);
                            PrintWriter scriptOut = new PrintWriter(new FileWriter("lfap.sh"));
                            scriptOut.println(exec);
                            scriptOut.close();
                            p = Runtime.getRuntime().exec("sh lfap.sh");
                            p.waitFor();
                            ts2 = System.currentTimeMillis();
                            System.out.println("Dataclient time time was " + (ts2 - ts1) / 1000 + " seconds.");
                            ts1 = ts2;
                            System.out.println("Command returned with exit code " + val);
                        } else {
                            System.out.println("Skipping: " + log.toString());
                        }
                        if (val != 0) {
                            System.out.println("Failed command line: " + exec);
                            Process p2 = Runtime.getRuntime().exec("perl sleep.pl");
                            int val2 = p2.waitFor();
                        } else {
                            PrintWriter out = new PrintWriter(new FileWriter(args[0]));
                            for (int x = 0; x < entries.length; x++)
                                out.println(entries[x]);
                            out.println(log);
                            out.close();
                        }
                    }
                }
                if (!didSomething) {
                    System.out.println("Sleeping...");
                    Process p = Runtime.getRuntime().exec("perl sleep.pl");
                    p.waitFor();
                }
            }

        } catch (Exception E) {
            E.printStackTrace();
        }
    }

}
